<template>
  <div>
    <div class="search">
      <input v-model="keyword" type="text" placeholder="输入城市名或拼音" class="search-input">
    </div>
    <div class="search-content" v-show="keyword" ref='wrapper'>
      <ul>
        <li class='search-item border-bottom' v-for="item of list" :key='item.id' @click='change(item.name)'>
          {{item.name}}
        </li>
        <li v-show="hasNoData">没有找到可匹配的城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    change (value) {
      this.changeCity(value)
      this.keyword = ''
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    hasNoData () {
      return this.list.length <= 0
    }
  },
  watch: {
    keyword (newValue) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!newValue) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        this.list = []
        for (let item in this.cities) {
          for (let i of this.cities[item]) {
            if (i.spell.includes(newValue) || i.name.includes(newValue)) {
              this.list.push(i)
            }
          }
        }
      }, 100)
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper, {
      click: true
    })
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/styles/varibles.styl';
.search
  height .72rem
  background $bgColor
  padding 0 .1rem
  .search-input
    width 100%
    border-radius .06rem
    height .62rem
    text-align center
    color #666
.search-content
  overflow hidden
  position absolute
  top 1.58rem
  left 0
  right 0
  bottom 0
  background #fdfdfd
  z-index 1
  .search-item
    line-height .62rem
    padding-left .2rem
    color #666
</style>>
